<template>
  <div class="container" v-cloak>
    <div class="nav">
      <div 
        class="nav-item" 
        :class="{'nav-item-act':index == showIndex}"
        v-for="(item, index) in navList" 
        :key="index * Math.random()"
        v-show="!item.hide"
        @click="changeSelect(index)"
      >
        {{item.lable}}
        <div class="close" v-show="item.canClose" @click.stop="close(index)">X</div>
      </div>
    </div>
    <div class="body">
      <slot></slot>
    </div>
  </div>  
</template>


<script>
export default {
  name: 'tab',
  data() {
    return {
      title: 'tab组件',
      navList: [],
      showIndex: 0
    }
  },
  methods: {
    getNavList() {
      let arr = []
      this.$children.map( (item,index) => {
        if(item.$options.name = 'pane') {
          let navItem = {
            lable: item.$attrs.lable || index,
            canClose: item.canClose,
            hide: false
          }
          this.navList.push(navItem)
        }
      })
    },
    changeSelect(index = 0) {
      this.showIndex = (index <= this.navList.length && index >= 0) ? index : 0
      this.$children.map( (item, Cindex) => {
        item.show = this.showIndex === Cindex
      })
    },
    close(index) {
      this.navList[index].hide = true
      //如果关闭的是当前选中项 则切换显示到一个未关闭的项
      if(index === this.showIndex) {
        this.navList.forEach((item, index) => {
          !item.hide && this.changeSelect(index)
        });
      }
    }
  },
  mounted() {
    this.getNavList()
    this.changeSelect(this.showIndex)
  },
}
</script>

<style lang="less" scoped>
[v-clock] {
  display: none;
}
@borderColor: #dedede;
.container {
  position: relative;
  width: 100%;
  .nav {
    width: 100%;
    border-bottom: 1px solid @borderColor;
    .nav-item {
      position: relative;
      display: inline-block;
      padding: 5px 10px;
      margin-right: 10px;
      font-size: 13px;
      border: 1px solid @borderColor;
      border-bottom: none;
      background-color: @borderColor;
      cursor: pointer;
      .close {
        position: absolute;
        top: -10px;
        right: -10px;
        width: 20px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        font-size: 12px;
        color: #fff;
        background-color: #bababa;
        border-radius: 50%;
      }
    }
    .nav-item:hover {
      background-color: #d6d6d6;
    }
    .nav-item-act {
      background-color: #fff;
      transform: translate(0px, 1px);
    }
    .nav-item-act:hover {
      background-color: #fff;
    }
  }
  .body {
    position: relative;
  }
}

</style>